﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace Pentakill
{
    public partial class Order : Form
    {
        
        SqlConnection con = new SqlConnection();
        public Order()
        {
            InitializeComponent();
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            con.ConnectionString = constr;
            con.Open();
            Loadallcombobox();
            LoadOrderInfo();
            defaultOrderform();
        }
        
        #region Code Orders

            bool ValidateOrder()
            {
                bool error = false;
                if (cmbOrderEmployee.Text.Length==0)
                {
                    errorProvider1.SetError(cmbOrderEmployee, "Please choose the required field \"Employee\" ");
                    error = true;
                }
                if (dtRequiredDate.Value.CompareTo(dtOrderDate.Value) < 0)
                {
                    errorProvider1.SetError(dtRequiredDate, "Required date must be greater than Order date");
                    error = true;
                }
                if (ckbShipperDate.Checked == true)
                {
                    if (dtShippedDate.Value.CompareTo(dtOrderDate.Value) < 0)
                    {
                        errorProvider1.SetError(dtShippedDate, "Shipped date must be greater than Order date");
                        error = true;
                    }
                }
                if (cmbShipperid.Text.Length == 0)
                {
                    errorProvider1.SetError(cmbShipperid, "Please choose the required field \"Shipper ID\" ");
                    error = true;
                }
                if (txtShipname.Text.Length == 0)
                {
                    errorProvider1.SetError(txtShipname, "Please enter the required field \"Ship Name\" ");
                    error = true;
                }
                if (txtShipaddress.Text.Length == 0)
                {
                    errorProvider1.SetError(txtShipaddress, "Please enter the required field \"Ship Address\" ");
                    error = true;
                }
                if (txtShipcity.Text.Length == 0)
                {
                    errorProvider1.SetError(txtShipcity, "Please enter the required field \"Ship City\" ");
                    error = true;
                }
                if (mtxtShipcode.Text.Trim().Length>0 && mtxtShipcode.MaskCompleted==false)
                {
                    errorProvider1.SetError(mtxtShipcode, "Please enter the field \"Ship Postal Code\" or blank the field ");
                    error = true;
                }
                if (cmbShipCountry.Text.Length == 0)
                {
                    errorProvider1.SetError(cmbShipCountry, "Please choose the required field \"Ship Country\" ");
                    error = true;
                }
                if (error)
                {
                    return false;
                }
                return true;
            }

            void defaultOrderform()
            {
                errorProvider1.Clear();
                txtOrderID.Text = "";
                cmbOrderCustomerid.SelectedIndex = -1;
                cmbOrderEmployee.SelectedIndex = -1;
                dtOrderDate.Value = DateTime.Now;
                dtRequiredDate.Value = DateTime.Now;
                dtShippedDate.Value = DateTime.Now;
                //cmbShipperid.SelectedIndex = -1;
                numFreight.Text = "0.01";
                txtShipname.Text = "";
                txtShipaddress.Text = "";
                txtShipcity.Text = "";
                txtShipRegion.Text = "";
                mtxtShipcode.Text = "";
                cmbShipCountry.Text = "";
                defaultOrderDetailsform();
                btnAdd.Enabled = true;
                btnUpdate.Enabled = false;
                btnDelete.Enabled = false;
                ckbShipperDate.Enabled = true;
                ckbShipperDate.Checked = false;
            }
           
            void LoadOrderInfo()
            {
                gvOrder.Rows.Clear();
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.Orders_get";
                    SqlDataReader dr = cmd.ExecuteReader();
                    DateTime dt;
                    while (dr.Read())
                    {
                        DateTime.TryParse(dr[3].ToString(),out dt);
                        string date1 = dt.ToShortDateString();
                        DateTime.TryParse(dr[4].ToString(),out dt);
                        string date2 = dt.ToShortDateString();
                        string date3 = "";
                        if (dr[5].ToString().Length != 0)
                        {
                            DateTime.TryParse(dr[5].ToString(), out dt);
                            date3 = dt.ToShortDateString();
                        }
                        gvOrder.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(),
                            date1, date2, date3, dr[6].ToString(),
                            dr[7].ToString(), dr[8].ToString(), dr[9].ToString(), dr[10].ToString(),
                            dr[11].ToString(), dr[12].ToString(), dr[13].ToString());
                    }
                    dr.Close();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void Loadallcombobox()
            {
                SqlDataAdapter da = new SqlDataAdapter("SELECT custid,companyname FROM Sales.Customers", con);
                DataTable dt = new DataTable("Customers");
                da.Fill(dt);
                cmbOrderCustomerid.ValueMember = "custid";
                cmbOrderCustomerid.DataSource = dt;
                cmbOrderCustomerid.DisplayMember = "companyname";
                da = new SqlDataAdapter("SELECT empid,firstname+' '+lastname AS fullname  FROM HR.Employees", con);
                dt = new DataTable("Employees");
                da.Fill(dt);
                cmbOrderEmployee.ValueMember = "empid";
                cmbOrderEmployee.DataSource = dt;
                cmbOrderEmployee.DisplayMember = "fullname";
                da = new SqlDataAdapter("SELECT shipperid, companyname  FROM Sales.Shippers", con);
                dt = new DataTable("Shipper");
                da.Fill(dt);
                cmbShipperid.ValueMember = "shipperid";
                cmbShipperid.DataSource = dt;
                cmbShipperid.DisplayMember = "companyname";
            }

            void InsertnewOrder()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.Orders_Insert";
                    SqlParameter param = new SqlParameter("@custid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderCustomerid.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@empid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderEmployee.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    DateTime dt;
                    param = new SqlParameter("@orderdate", SqlDbType.DateTime);
                    DateTime.TryParse(dtOrderDate.Value.ToShortDateString(), out dt);
                    param.Value = dt.ToShortTimeString();
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@requireddate", SqlDbType.DateTime);
                    DateTime.TryParse(dtRequiredDate.Value.ToShortDateString(), out dt);
                    param.Value = dt.ToShortTimeString();
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shippeddate", SqlDbType.DateTime);
                    if (ckbShipperDate.Checked == true)
                    {
                        DateTime.TryParse(dtShippedDate.Value.ToShortDateString(), out dt);
                        param.Value = dt.ToShortTimeString();
                    }
                    else
                    {
                        param.Value = System.Convert.DBNull;
                    }
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipperid", SqlDbType.Int);
                    param.Value = int.Parse(cmbShipperid.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@freight", SqlDbType.Money);
                    param.Value = decimal.Parse(numFreight.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipname", SqlDbType.NVarChar, 40);
                    param.Value = txtShipname.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipaddress", SqlDbType.NVarChar, 60);
                    param.Value = txtShipaddress.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipcity", SqlDbType.NVarChar, 15);
                    param.Value = txtShipcity.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipregion", SqlDbType.NVarChar, 15);
                    param.Value = txtShipRegion.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shippostalcode", SqlDbType.NVarChar, 10);
                    param.Value = mtxtShipcode.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipcountry", SqlDbType.NVarChar, 15);
                    param.Value = cmbShipCountry.Text;
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadOrderInfo();
                    MessageBox.Show("Insert successed!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void UpdateOrder()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.Orders_Update";
                    SqlParameter param = new SqlParameter("@orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderID.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@custid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderCustomerid.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@empid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderEmployee.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    DateTime dt;
                    param = new SqlParameter("@orderdate", SqlDbType.DateTime);
                    DateTime.TryParse(dtOrderDate.Value.ToShortDateString(), out dt);
                    param.Value = dt.ToString();
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@requireddate", SqlDbType.DateTime);
                    DateTime.TryParse(dtRequiredDate.Value.ToShortDateString(), out dt);
                    param.Value = dt.ToString();
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shippeddate", SqlDbType.DateTime);
                    if (ckbShipperDate.Checked == true)
                    {
                        DateTime.TryParse(dtShippedDate.Value.ToShortDateString(), out dt);
                        param.Value = dt.ToString();
                    }
                    else
                    {
                        param.Value = System.Convert.DBNull;
                    }
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipperid", SqlDbType.Int);
                    param.Value = int.Parse(cmbShipperid.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@freight", SqlDbType.Money);
                    param.Value = decimal.Parse(numFreight.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipname", SqlDbType.NVarChar, 40);
                    param.Value = txtShipname.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipaddress", SqlDbType.NVarChar, 60);
                    param.Value = txtShipaddress.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipcity", SqlDbType.NVarChar, 15);
                    param.Value = txtShipcity.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipregion", SqlDbType.NVarChar, 15);
                    param.Value = txtShipRegion.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shippostalcode", SqlDbType.NVarChar, 10);
                    param.Value = mtxtShipcode.Text;
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@shipcountry", SqlDbType.NVarChar, 15);
                    param.Value = cmbShipCountry.Text;
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadOrderInfo();
                    MessageBox.Show("Update successed!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void DeleteOrder()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.Orders_Delete";
                    SqlParameter param = new SqlParameter("@orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderID.Text);
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadOrderInfo();
                    MessageBox.Show("Delete successed!");
                }
                catch (Exception)
                {
                    MessageBox.Show("Have any data is used in other form\nCan not delete the order","ERROR",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

        #endregion
        
        #region Code Order Details

            bool ValidateInputOrderDetail()
            {
                bool error = false;
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_search";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderDid.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderDProductID.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    SqlDataReader dd = cmd.ExecuteReader();
                    if (dd.Read() == true)
                    {
                        errorProvider1.SetError(cmbOrderDProductID, "The product is existed!\n Please choose other product");
                        error = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
                if (error==true)
                {
                    return false;
                }
                return true;
            }

            void LoadNewProductID()
            {
                SqlDataAdapter da = new SqlDataAdapter("SELECT productid,productname FROM Production.Products", con);
                DataTable dt = new DataTable("Products");
                da.Fill(dt);
                cmbOrderDProductID.ValueMember = "productid";
                cmbOrderDProductID.DisplayMember = "productname";
                cmbOrderDProductID.DataSource = dt;
            }

            void LoadProduct_selected(string id)
            {
                cmbOrderDProductID.DataSource = null;
                string str = string.Format("SELECT a.*,b.productname AS Name,b.productid AS ID FROM Sales.OrderDetails a, Production.Products b WHERE '{0}'=a.orderid AND a.productid=b.productid",id);
                SqlDataAdapter da = new SqlDataAdapter(str, con);
                DataTable dd = new DataTable("Products");
                da.Fill(dd);
                cmbOrderDProductID.ValueMember = "ID";
                cmbOrderDProductID.DisplayMember = "Name";
                cmbOrderDProductID.DataSource = dd;
            }

            void defaultOrderDetailsform()
            {
                errorProvider1.Clear();
                cmbOrderDProductID.Text = "";
                cmbOrderDProductID.DataSource = null;
                cmbOrderDProductID.Items.Clear();
                txtOrderDPrice.Text = "";
                numOrderDQuantity.Text = "0";
                numOrderDDiscount.Text = "0";
                txtOrderDTotal.Text = "";
                gvDetails.Rows.Clear();
                DateTime dt=DateTime.Parse(dtShippedDate.Value.ToString());
                DateTime now=DateTime.Now;
                if (ckbShipperDate.Checked == true && (now-dt).Days>1)
                {
                    btnUpdate.Enabled = false;
                }
                else
                {
                    btnUpdate.Enabled = true;
                }
            }
            
            void LoadOrderDetailsInfo(string orderid)
            {
                gvDetails.Rows.Clear();
                Double total, all = 0;
                Double price;
                int quantity;
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_get";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(orderid);
                    cmd.Parameters.Add(param);
                    SqlDataReader dd = cmd.ExecuteReader(); 
                    while (dd.Read())
                    {
                        price = Double.Parse(dd[2].ToString());
                        quantity=int.Parse(dd[3].ToString());
                        total = price * (quantity) - (double.Parse(dd[4].ToString()) * price*quantity);
                        gvDetails.Rows.Add(dd[1].ToString(), dd[2].ToString(),
                            dd[3].ToString(), dd[4].ToString(), total);
                        all += total;
                    }
                    dd.Close();
                    LoadProduct_selected(orderid);
                    txtOrderDTotal.Text = "" + all;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }
            
            void SearchOrderDetail(string Orderid, string productid)
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_search";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(Orderid);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(productid);
                    cmd.Parameters.Add(param);
                    SqlDataReader dd = cmd.ExecuteReader();
                    if (dd.Read() == true)
                    {
                        txtOrderDPrice.Text = dd[2].ToString();
                        numOrderDQuantity.Text = dd[3].ToString();
                        numOrderDDiscount.Text = ""+(double.Parse(dd[4].ToString())*100);
                        double price = double.Parse(txtOrderDPrice.Text);
                        int quantity = int.Parse(numOrderDQuantity.Text);
                        double total = price * (quantity) - (double.Parse(dd[4].ToString()) * price*quantity);
                        txtOrderDTotal.Text = "" + total;
                    }
                    dd.Close();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void SearchPriceDetail(string Productid)
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_searchprice";
                    SqlParameter param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(Productid);
                    cmd.Parameters.Add(param);
                    SqlDataReader dd = cmd.ExecuteReader();
                    if (dd.Read() == true)
                    {
                        txtOrderDPrice.Text = dd[0].ToString();
                    }
                    dd.Close();
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void InsertOrderDetailInfo()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_Insert";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderDid.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderDProductID.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@UnitPrice", SqlDbType.Money);
                    param.Value = decimal.Parse(txtOrderDPrice.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Quantity", SqlDbType.SmallInt);
                    param.Value = short.Parse(numOrderDQuantity.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Discount", SqlDbType.Decimal);
                    param.Precision = 4;
                    param.Scale = 3;
                    param.Value = decimal.Parse("" + (double.Parse(numOrderDDiscount.Value.ToString()) / 100));
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadProduct_selected(txtOrderDid.Text);
                    MessageBox.Show("Insert successed!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("The product have exist in Order\nCan not insert the products", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void UpdateOrderDetailInfo()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_Update";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderDid.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderDProductID.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@UnitPrice", SqlDbType.Money);
                    param.Value = decimal.Parse(txtOrderDPrice.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Quantity", SqlDbType.SmallInt);
                    param.Value = short.Parse(numOrderDQuantity.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Discount", SqlDbType.Decimal);
                    param.Precision = 4;
                    param.Scale = 3;
                    param.Value = decimal.Parse("" + (double.Parse(numOrderDDiscount.Value.ToString()) / 100));
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadProduct_selected(txtOrderDid.Text);
                    MessageBox.Show("Update successed!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }

            void DeleteOrderDetailInfo()
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "Sales.OrderDetails_Delete";
                    SqlParameter param = new SqlParameter("@Orderid", SqlDbType.Int);
                    param.Value = int.Parse(txtOrderDid.Text);
                    cmd.Parameters.Add(param);
                    param = new SqlParameter("@Productid", SqlDbType.Int);
                    param.Value = int.Parse(cmbOrderDProductID.SelectedValue.ToString());
                    cmd.Parameters.Add(param);
                    cmd.ExecuteNonQuery();
                    LoadProduct_selected(txtOrderDid.Text);
                    MessageBox.Show("Delete successed!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Open();
                }
            }
            
        #endregion

        #region Code Shippers

            void openformShipper()
            {
                Shipper sp = new Shipper(cmbShipperid.SelectedValue.ToString());
                sp.ShowDialog(this);
                String shipperid = sp.returnstringfororder();
                if (shipperid.Length != 0)
                {
                    cmbShipperid.SelectedValue = shipperid;
                }
            }

        #endregion
        
        #region Action Orders

            private void Order_FormClosing(object sender, FormClosingEventArgs e)
            {
                this.Hide();
                this.Parent = null;
                e.Cancel = true;
                con.Close();
            }

            private void gvOrder_SelectionChanged(object sender, EventArgs e)
            {
                if (gvOrder.SelectedRows.Count > 0)
                {
                    btnAdd.Enabled = false;
                    btnUpdate.Enabled = true;
                    btnDelete.Enabled = true;
                    DataGridViewRow dg = gvOrder.SelectedRows[0];
                    txtOrderID.Text = dg.Cells[0].Value.ToString();
                    cmbOrderCustomerid.Text = dg.Cells[1].Value.ToString();
                    cmbOrderEmployee.Text = dg.Cells[2].Value.ToString();
                    DateTime dt;
                    DateTime.TryParse(dg.Cells[3].Value.ToString(), out dt);
                    dtOrderDate.Value = dt;
                    DateTime.TryParse(dg.Cells[4].Value.ToString(), out dt);
                    dtRequiredDate.Value = dt;
                    if (dg.Cells[5].Value.ToString().Length==0)
                    {
                        ckbShipperDate.Checked = false;
                        ckbShipperDate.Enabled = true;
                    }
                    else
                    {
                        DateTime.TryParse(dg.Cells[5].Value.ToString(), out dt);
                        dtShippedDate.Value = dt;
                        ckbShipperDate.Checked = true;
                        ckbShipperDate.Enabled = false;
                    }
                    cmbShipperid.Text = dg.Cells[6].Value.ToString();
                    numFreight.Text = dg.Cells[7].Value.ToString();
                    txtShipname.Text = dg.Cells[8].Value.ToString();
                    txtShipaddress.Text = dg.Cells[9].Value.ToString();
                    txtShipcity.Text = dg.Cells[10].Value.ToString();
                    txtShipRegion.Text = dg.Cells[11].Value.ToString();
                    mtxtShipcode.Text = dg.Cells[12].Value.ToString();
                    cmbShipCountry.Text = dg.Cells[13].Value.ToString();
                    grpDetails.Enabled = true;
                    defaultOrderDetailsform();
                    txtOrderDid.Text = txtOrderID.Text;
                    LoadOrderDetailsInfo(txtOrderID.Text);
                }
            }

            private void txtShipcode_KeyDown(object sender, KeyEventArgs e)
            {
                errorProvider1.Clear();
                if (e.KeyCode != Keys.Back && (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9))
                {
                    e.SuppressKeyPress = true;
                    errorProvider1.SetError(mtxtShipcode, "Field must be Number");
                }
            }
            
            private void Order_Load(object sender, EventArgs e)
            {

            }

            private void btnNew_Click(object sender, EventArgs e)
            {
                DialogResult rs = MessageBox.Show("Are you sure to clear form?", "Confirm",
                   MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    defaultOrderform();
                }
            }

            private void ckbShipperDate_CheckedChanged(object sender, EventArgs e)
            {
                if (ckbShipperDate.Checked == true)
                {
                    dtShippedDate.Enabled = true;
                    btnOrderDAdd.Enabled = false;
                    btnOrderDUpdate.Enabled = false;
                    btnOrderDDelete.Enabled = false;
                    btnOrderDNew.Enabled = false;
                }
                else
                {
                    dtShippedDate.Enabled = false;
                    btnOrderDAdd.Enabled = true;
                    btnOrderDUpdate.Enabled = false;
                    btnOrderDDelete.Enabled = false;
                    btnOrderDNew.Enabled = true;
                }
            }

            private void btnAdd_Click(object sender, EventArgs e)
            {
                errorProvider1.Clear();
                if (ValidateOrder())
                {
                    InsertnewOrder();
                    defaultOrderform();
                }
            }

            private void btnUpdate_Click(object sender, EventArgs e)
            {
                errorProvider1.Clear();
                if (ValidateOrder())
                {
                    DialogResult rs = MessageBox.Show("Are you sure to update?", "Confirm",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (rs == DialogResult.Yes)
                    {
                        UpdateOrder();
                        defaultOrderform();
                    }
                }

            }

            private void btnDelete_Click(object sender, EventArgs e)
            {
                DialogResult rs = MessageBox.Show("Are you sure to delete?", "Confirm",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    DeleteOrder();
                    defaultOrderform();
                }

            }

            private void txtSearch_TextChanged(object sender, EventArgs e)
            {
                if (txtSearch.Text.Length == 0)
                {
                    LoadOrderInfo();
                    defaultOrderform();
                }
                else
                {
                    DataGridViewRow dr;
                    bool show;
                    for (int i = 0; i < gvOrder.Rows.Count; i++)
                    {
                        show = false;
                        dr = gvOrder.Rows[i];
                        dr.Visible = true;
                        for (int j = 0; j < 14; j++)
                        {
                            dr.Cells[j].Style.BackColor = Color.White;
                            if (dr.Cells[j].Value.ToString().ToLower().Contains(txtSearch.Text.ToLower()) == true)
                            {
                                dr.Cells[j].Style.BackColor = Color.Yellow;
                                show = true;
                            }
                        }
                        if (show == false)
                        {
                            dr.Visible = false;
                        }
                    }
                    defaultOrderform();
                }
            }
       
        #endregion

        #region Action Order Details

            private void btnOrderDmode_Click(object sender, EventArgs e)
            {
                btnOrderDmode.Visible = false;
                btnOrderDmode2.Visible = true;
                gvDetails.Visible = false;
                if (gvDetails.SelectedRows.Count > 0)
                {
                    DataGridViewRow dr = gvDetails.SelectedRows[0];
                    cmbOrderDProductID.SelectedValue = dr.Cells[0].Value.ToString();
                }
            }
            
            private void btnOrderDmode2_Click(object sender, EventArgs e)
            {
                if (cmbOrderDProductID.DataSource != null)
                {
                    cmbOrderDProductID.DataSource = null;
                }
                btnOrderDmode.Visible = true;
                btnOrderDmode2.Visible = false;
                gvDetails.Visible = true;
                if (txtOrderDid.Text.Length > 0)
                {
                    LoadOrderDetailsInfo(txtOrderDid.Text);
                }
            }
            
            private void btnOrderDNew_Click(object sender, EventArgs e)
            {
                DialogResult rs = MessageBox.Show("Are you sure to clear detail?", "Confirm",
                   MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    defaultOrderDetailsform();
                    LoadNewProductID();
                    if (ckbShipperDate.Checked == false)
                    {
                        btnOrderDAdd.Enabled = true;
                        btnOrderDDelete.Enabled = false;
                        btnOrderDUpdate.Enabled = false;
                    }
                }
            }
            
            private void cmbOrderDProductID_TextChanged(object sender, EventArgs e)
            {
                try
                {
                    if (cmbOrderDProductID.Text.Length > 0 && txtOrderDid.Text.Length > 0 && gvDetails.Rows.Count > 0)
                    {
                        SearchOrderDetail(txtOrderDid.Text, cmbOrderDProductID.SelectedValue.ToString());
                    } 
                    if (cmbOrderDProductID.Text.Length > 0 && txtOrderDid.Text.Length > 0 && gvDetails.Rows.Count == 0)
                    {
                        SearchPriceDetail(cmbOrderDProductID.SelectedValue.ToString());
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }

            private void btnOrderDAdd_Click(object sender, EventArgs e)
            {
                errorProvider1.Clear();
                if (ValidateInputOrderDetail())
                {
                    InsertOrderDetailInfo();
                }
            }

            private void btnOrderDUpdate_Click(object sender, EventArgs e)
            {
                DialogResult rs = MessageBox.Show("Are you sure to update?", "Confirm",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    UpdateOrderDetailInfo();
                }
            }

            private void btnOrderDDelete_Click(object sender, EventArgs e)
            {
                DialogResult rs = MessageBox.Show("Are you sure to delete?", "Confirm", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    DeleteOrderDetailInfo();
                }
            }

            private void gvDetails_SelectionChanged(object sender, EventArgs e)
            {
                if (ckbShipperDate.Checked == false)
                {
                    btnOrderDAdd.Enabled = false;
                    btnOrderDDelete.Enabled = true;
                    btnOrderDUpdate.Enabled = true;
                }
            }

        #endregion
        
        #region Action Shippers

            private void btnViewShipper_Click(object sender, EventArgs e)
            {
                openformShipper();
            }

        #endregion

            


           
    }
}
